package com.imgo.max.experience.service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.imgo.max.artist.dto.DevoteInfo;
import com.imgo.max.common.util.ObjectUtil;
import com.imgo.max.livemonitor.dto.LiveMonitorKPIDto;

/**
 * Created by peter on 09/09/16.
 */
public class LiveMonitorListener implements MessageListener {
    Logger logger = LoggerFactory.getLogger(LiveMonitorListener.class);

    @Resource
    ExperienceMessageServiceImpl experienceMessageServiceImpl;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        byte[] body = message.getBody();
        String msgId = message.getMsgID();
        String tag = message.getTag();
        try {
        	//在线峰值
        	LiveMonitorKPIDto dto = (LiveMonitorKPIDto) ObjectUtil.toObject(body);
        	DevoteInfo linvLengthDevote = new DevoteInfo();
        	linvLengthDevote.setArtistUid(dto.getUid());
        	linvLengthDevote.setUid("");
        	long onlineTop = Math.round(dto.getOnlinePeopleTop() / 30);
        	if (onlineTop < 1)
        	{
        		onlineTop = 1;
        	}
        	linvLengthDevote.setDevoteValue(Math.round(onlineTop)); //在线峰值
        	logger.error("直播结束，通过在线峰值增加经验{},在线峰值是{}", linvLengthDevote.getDevoteValue(), dto.getOnlinePeopleTop());
    		// 贡献值来源 － 0:加粉丝 1:礼物 2:守护 3:直播时长 4:观看人数 5:每次直播峰值
        	linvLengthDevote.setType(5);
        	linvLengthDevote.setTime(new Timestamp(System.currentTimeMillis()));
        	experienceMessageServiceImpl.updateExperience(ObjectUtil.toByteArray(linvLengthDevote));
        	
        	//直播时长
        	DevoteInfo devote = new DevoteInfo();
    		devote.setArtistUid(dto.getUid());
    		devote.setType(3);
    		devote.setUid("");
    		//直播开始的时候也有消息，所以此时结束时间为空
    		if (dto.getEndTime() != null)
    		{
    			long length = (dto.getEndTime().getTime() - dto.getStartTime().getTime())/1000/60; //得到分钟数
    			devote.setDevoteValue(Math.round(length*10)); //直播时长,1分钟等于10经验
    			logger.error("直播结束，通过直播时长增加经验{}, 消息ID {}", devote.getDevoteValue(), msgId);
    			devote.setTime(new Timestamp(System.currentTimeMillis()));
    			experienceMessageServiceImpl.updateExperience(ObjectUtil.toByteArray(devote));
    		}
        	//观看人数加经验不做了
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return Action.CommitMessage;
    }
    
}
